import datetime
import random
import time

from selenium.webdriver import Keys
from selenium.webdriver.support.select import Select


class SeleniumUtils:
    @staticmethod
    def slow_typing(element, text, delay=0.2):
        for char in text:
            element.send_keys(char)
            time.sleep(delay)  # 模拟人类输入的间隔（单位：秒）

    @staticmethod
    def human_typing(element, text, min_delay=0.1, max_delay=0.3):
        for char in text:
            element.send_keys(char)
            time.sleep(random.uniform(min_delay, max_delay))

    @staticmethod
    def paste_input(element, text):
        element.click()
        element.send_keys(Keys.CONTROL, 'a')
        element.send_keys(Keys.DELETE)
        element.send_keys(text)

    @staticmethod
    def fast_input(element, text):
        element.send_keys(text)

    @staticmethod
    def random_select(select_element):
        select_element.click()
        time.sleep(1)  # 等待下拉菜单展开
        select = Select(select_element)
        options = select.options
        valid_options = [option for option in options if option.get_attribute('value')]
        random_option = random.choice(valid_options)
        value = random_option.get_attribute('value')
        select.select_by_value(value)

    @staticmethod
    def random_select_age(year_select):
        year_select.click()
        time.sleep(1)  # 等待下拉菜单展开
        # 获取当前年份
        current_year = datetime.datetime.now().year
        # 计算18岁及以上的最大出生年份
        max_birth_year = current_year - 18
        select = Select(year_select)
        options = select.options
        # 筛选出符合条件的年份选项
        valid_options = []
        for option in options:
            value = option.get_attribute('value')
            if value.isdigit():
                year = int(value)
                if year <= max_birth_year:
                    valid_options.append(option)
        # 随机选择一个符合条件的年份
        if valid_options:
            selected_option = random.choice(valid_options)
            print(f'已选择出生年份：{selected_option.text}')
            select.select_by_value(selected_option.get_attribute('value'))
        else:
            print('未找到符合条件的出生年份选项。')

    @classmethod
    def scroll(cls, web_driver, start_y=400, end_y=100, x=200):
        js = f"""
                let touchstart = new TouchEvent('touchstart', {{
                    touches: [new Touch({{ identifier: 1, target: document.body, clientX: {x}, clientY: {start_y} }})]
                }});
                let touchmove = new TouchEvent('touchmove', {{
                    touches: [new Touch({{ identifier: 1, target: document.body, clientX: {x}, clientY: {end_y} }})]
                }});
                let touchend = new TouchEvent('touchend');

                document.body.dispatchEvent(touchstart);
                document.body.dispatchEvent(touchmove);
                document.body.dispatchEvent(touchend);
            """
        web_driver.execute_script(js)
